<?php

namespace App\Jobs;

use App\Models\Posts\WxPost;
use App\Models\Posts\WxPostsTag;
use App\Wen\Utils\StatisticUtils;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class SitemapUpdateJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $common_base_post_url = '';
    protected $common_base_topic_url = '';
    protected $common_base_circle_url = '';
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
        $this->common_base_post_url = env('APP_URL') . '/single/';
        $this->common_base_topic_url = env('APP_URL') . '/tag/';
        $this->common_base_circle_url = env('APP_URL') . '/circle/';
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $post_total = StatisticUtils::total_post_count();
        $pages = (int)($post_total / 1000 ) + 1;
        for ($i = 0; $i < $pages; $i ++){
            $page_posts = WxPost::where([
                ['id', '>', 0], ['id', '<', 1000],['posts_state', '=', 0]
            ])->orderBy('id', 'asc')->limit(1000)->get(['id', 'circle_id']);
            $needle_urls = [];
            if($page_posts) {
                foreach ($page_posts as $post) {
                    $tagsIds = WxPostsTag::where('posts_id', $post->id)->pluck('tags_id');//话题ID列表
                    if ($tagsIds) {
                        foreach ($tagsIds as $tag_id) {
                            $needle_urls[] = $this->common_base_topic_url . $tag_id;
                        }
                    }
                    $needle_urls[] = $this->common_base_circle_url . $post->circle_id;

                    $needle_urls[] = $this->common_base_post_url . $post->id;
                }

                // 去重
                $needle_urls = array_unique($needle_urls);

                $file_name = 'sitemap' . ($i > 0 ? '-'.$i : ''). '.txt';
                $path = public_path( $file_name );
                @unlink($path);
                $file = fopen($path, 'w');

                $file_str = '';
                if($needle_urls){
                    foreach ($needle_urls as $url){
                        $file_str .= $url."\n";
                    }
                }

                fwrite($file, $file_str);
                fclose($file);

                $xml = '<?xml version="1.0" encoding="UTF-8"?>'.PHP_EOL;
                $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'.PHP_EOL;

                $xml .= '<url>'.PHP_EOL;
                $xml .= '<loc>'.env('APP_URL').'</loc>'.PHP_EOL;//网站首页地址
                $xml .= '<lastmod>'.date('Y-m-d').'</lastmod>'.PHP_EOL;
                $xml .= '<changefreq>always</changefreq>'.PHP_EOL;
                $xml .= '<priority>1.0</priority>'.PHP_EOL;
                $xml .= '</url>'.PHP_EOL;

                foreach($needle_urls as $url) {
                    $xml .= '<url>'.PHP_EOL;
                    $xml .= '<loc>'.$url.'</loc>'.PHP_EOL;//拼接文章列表页链接地址
                    $xml .= '<lastmod>'.date('Y-m-d').'</lastmod>'.PHP_EOL;
                    $xml .= '<changefreq>always</changefreq>'.PHP_EOL;
                    $xml .= '<priority>0.9</priority>'.PHP_EOL;
                    $xml .= '</url>'.PHP_EOL;
                }

                $xml .= '</urlset>';

                $xml_name = 'sitemap' . ($i > 0 ? '-'.$i : ''). '.xml';
                $xml_path = public_path( $xml_name );
                @unlink($xml_path);
                $file = fopen($xml_path, 'w');
                fwrite($file, $xml);
                fclose($file);

                _logger_(__file__, __line__,  $file_name."\n".$xml_name);

            }
        }
    }
}
